package com.cloud.service.consumetype.impl;

import com.cloud.commons.constants.ConsumeConstant;
import com.cloud.dao.consumetype.ConsumeTypeDao;
import com.cloud.model.entity.consumetype.ConsumeType;
import com.cloud.model.view.consumetype.ConsumeTypeView;
import com.cloud.service.consumetype.ConsumeTypeService;
import com.cloud.commons.utils.CloudCopyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
* <b><code>ConsumeTypeImpl</code></b>
* <p/>
* ConsumeType的具体实现
* <p/>
* <b>Creation Time:</b> 2019-10-15 17:23:42.
*
* @author ${model.author}
* @version 1.0.0
* @since cloud-spring-boot-be 1.0.0
*/
@Service
public class ConsumeTypeServiceImpl implements ConsumeTypeService {

    /**
     * The Constant LOG.
     */
    private static final Logger LOG = LoggerFactory
            .getLogger(ConsumeTypeServiceImpl.class);

    @Autowired
    private ConsumeTypeDao consumeTypeDao;

    @Override
    public ConsumeTypeView getEntity(long id) {
        // 获取Entity
        ConsumeType consumeType = consumeTypeDao.findById(id).orElseThrow(() -> new RuntimeException("获取不到id为：" + id + "的数据记录"));
        // 复制Dao层属性到view属性
        ConsumeTypeView consumeTypeView = new ConsumeTypeView();
        CloudCopyUtils.copyBean(consumeType, consumeTypeView);
        return consumeTypeView;
    }

    @Override
    public long getEntitiesCount() {
        return consumeTypeDao.count();
    }

    @Override
    public List<ConsumeTypeView> findAll() {
        List<ConsumeTypeView> consumeTypeViews = new ArrayList<>();
        List<ConsumeType> consumeTypes = consumeTypeDao.findAll();
        for (ConsumeType consumeType : consumeTypes){
            ConsumeTypeView consumeTypeView = new ConsumeTypeView();
            CloudCopyUtils.copyBean(consumeType, consumeTypeView);
            consumeTypeViews.add(consumeTypeView);
        }
        return consumeTypeViews;
    }

    @Override
    public ConsumeTypeView saveEntity(ConsumeTypeView consumeTypeView)  {
        // 保存的业务逻辑
        ConsumeType consumeType = new ConsumeType();
        CloudCopyUtils.copyBean(consumeTypeView, consumeType);
        // user数据库映射传给dao进行存储
        consumeType.setCreateTime(System.currentTimeMillis());
        consumeType.setUpdateTime(System.currentTimeMillis());
        consumeType.setWeight(System.currentTimeMillis());
        consumeType.setEnabled(1);
        consumeTypeDao.save(consumeType);
        CloudCopyUtils.copyBean(consumeType,consumeTypeView);
        return consumeTypeView;
    }

    @Override
    public void deleteEntity(long id) {
        ConsumeType consumeType = consumeTypeDao.findById(id).orElseThrow(() -> new RuntimeException("获取不到id为：" + id + "的数据记录"));
        consumeType.setId(id);
        consumeTypeDao.delete(consumeType);
    }

    @Override
    @Transactional(rollbackOn = { Exception.class })
    public void deleteEntities(String ids) {
        String[] entityIds= ids.split("\\,");
        List<ConsumeType> consumeTypes = new ArrayList<>();
        for(String entityId : entityIds){
            ConsumeType consumeType = new ConsumeType();
            consumeType.setId(Long.valueOf(entityId));
            consumeTypes.add(consumeType);
        }
        consumeTypeDao.deleteInBatch(consumeTypes);
    }

    @Override
    public void updateEntity(ConsumeTypeView consumeTypeView) {
        Specification<ConsumeType> consumeTypeSpecification = Optional.ofNullable(consumeTypeView).map( s -> {
            return new Specification<ConsumeType>() {
                @Override
                public Predicate toPredicate(Root<ConsumeType> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicates = new ArrayList<>();
                    // id
                    predicates.add(criteriaBuilder.equal(root.get("id").as(Long.class), s.getId()));

                    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                    return criteriaQuery.getRestriction();
                }
            };
        }).orElseThrow(()->new IllegalArgumentException("ConsumeTypeView is null"));


        // 获取原有的属性，把不变的属性覆盖
        Optional<ConsumeType> consumeTypeOptionalBySearch = consumeTypeDao.findOne(consumeTypeSpecification);
        consumeTypeOptionalBySearch.map(consumeTypeBySearch -> {
            CloudCopyUtils.copyBeanExcludeNull(consumeTypeView,consumeTypeBySearch);
            consumeTypeBySearch.setUpdateTime(System.currentTimeMillis());
            consumeTypeDao.save(consumeTypeBySearch);
            return "";
        }).orElseThrow(()->new RuntimeException("无法找到id为" + consumeTypeView.getId() + "的数据记录"));
    }

    @Override
    public List<ConsumeTypeView> getAllEntityByType(Integer type) {
        List<ConsumeType> consumeTypes = consumeTypeDao.findAllByEnabledAndTypeOrderByWeightDesc(ConsumeConstant.ENABLED,type);
        List<ConsumeTypeView> consumeTypeViews = new ArrayList<>();
        if (ObjectUtils.isEmpty(consumeTypes) || consumeTypes.size() == 0) {
            return consumeTypeViews;
        }
        for (ConsumeType consumeType:consumeTypes) {
            ConsumeTypeView consumeTypeView = new ConsumeTypeView();
            CloudCopyUtils.copyBean(consumeType,consumeTypeView);
            consumeTypeViews.add(consumeTypeView);
        }
        return consumeTypeViews;
    }
}
